package javaweb.exception;


/*
* 全局异常处理器
* */

import javaweb.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    private DeleteException deleteException;

    @ExceptionHandler
    public Result handlerException(Exception e) {

        log.error("出错了，信息为:", e);
        return Result.error("出错了，请联系管理人员");
    }

    @ExceptionHandler
    public Result handlerDuplicateKeyException(DuplicateKeyException e){
        log.error("出错了:信息为", e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMessage = message.substring(i);
        String[] arr = errMessage.split(" ");
        return Result.error(arr[2] + "已存在");
    }

    @ExceptionHandler
    public Result handlerDeleteException(DeleteException e) {
        log.error("出错了，信息为：", e);
        return Result.error("对不起, 该班级下有学生, 不能直接删除");
    }

    @ExceptionHandler
    public Result handlerLoginException(LoginException e) {
        log.error("出错了，信息为：", e);
        return Result.error("用户名或密码错误");
    }



}
